package cn.fabrice.controller;

import cn.fabrice.common.BaseResponse;
import cn.fabrice.common.ErrorCode;
import cn.fabrice.constant.MessageConstant;
import cn.fabrice.constant.UserConstant;
import cn.fabrice.dto.UserLoginDTO;
import cn.fabrice.dto.UserQueryDTO;
import cn.fabrice.dto.UserRegisterDTO;
import cn.fabrice.exception.BusinessException;
import cn.fabrice.model.User;
import cn.fabrice.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterDTO userRegisterDTO){
        log.info("用户注册，{}",userRegisterDTO);
        Long id = userService.userRegister(userRegisterDTO.getAccount(), userRegisterDTO.getPassword(), userRegisterDTO.getCheckPassword());
        return BaseResponse.success(id);
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request){
        log.info("用户登录，{}，{}",userLoginDTO,request);
        User user = userService.userLogin(userLoginDTO.getAccount(), userLoginDTO.getPassword(), request);
        log.info("登录成功，{}",user);
        return BaseResponse.success(user);
//        return user;
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<String> logout(HttpServletRequest request){
        log.info("用户退出");
        if(request == null){
            return BaseResponse.error(ErrorCode.NOLL_ERROR);
        }
        //todo 看一下前端是否会用到这个id，如果用不到就修改一下返回值
        Integer id = userService.userLogout(request);
        return BaseResponse.success();
    }
    /**
     * 用户查询
     * @param userQueryDTO
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> search (UserQueryDTO userQueryDTO, HttpServletRequest request){
        log.info("用户查询，{}",userQueryDTO);
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN);
        if(userObj == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(!checkedType(request)){
            return BaseResponse.error(ErrorCode.NOT_AUTO);
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNoneBlank(userQueryDTO.getName())){
            userQueryWrapper.like("name",userQueryDTO.getName());
        }
        List<User> list = userService.list(userQueryWrapper);
        return BaseResponse.success(list);

    }

    /**
     * 用户删除
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> delete(@PathVariable  Long id, HttpServletRequest request){
        log.info("用户删除，{}",id);
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN);
        if(userObj == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(!checkedType(request)){
            //todo 这里原来是要返回false的，这里换了因为error中没有data传递，注意一下前后端联调时的错误
            return BaseResponse.error(ErrorCode.NOT_AUTO);
        }
        boolean isDelete = userService.deleteById(id);
        return BaseResponse.success(isDelete); //这个就是逻辑删除
    }

    /**
     * 获取用户的登录态
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> loginState(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN);
        User user = (User) userObj;
        if (user == null ){
            return BaseResponse.error(ErrorCode.NOT_LOGIN);
        }
        //session中的user不一定是最新的，所以需要去查库
        User DBuser = userService.getById(user.getId());
        //todo 校验用户是否合法
        User safetyUser = userService.getSafetyUser(DBuser);
        return BaseResponse.success(safetyUser);
    }

    /**
     * 是否为管理员
     * @param request
     * @return
     */
    public boolean checkedType(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN);
        User user = (User) userObj;
        if(user.getType().equals(UserConstant.TYPE_USER)){
            log.info(MessageConstant.TYPE_ERROR);
            return false;
        }
        return true;
    }

}
